package com.csun.cmny.provider.controller;

import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dao.OmcNursingRoomBindMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.OldOutConstant;
import com.csun.cmny.provider.model.domain.OmcNursingUserBind;
import com.csun.cmny.provider.model.dto.old_out.*;
import com.csun.cmny.provider.model.dto.revise.GroupPaymentFeeQueryDto;
import com.csun.cmny.provider.model.vo.RpcRoleVo;
import com.csun.cmny.provider.model.vo.old_out.OldOutDaysVo;
import com.csun.cmny.provider.model.vo.old_out.OldOutOldmanVo;
import com.csun.cmny.provider.model.vo.old_out.OldOutVo;
import com.csun.cmny.provider.model.vo.revise.GroupPaymentFeeVo;
import com.csun.cmny.provider.pojo.NursingGroup;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.vo.MyCommentVo;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author chenzheng
 * @description:出院流程控制器
 * @date 2019/9/11
 */
@Slf4j
@RestController
@RequestMapping(value = "/oldOut", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class OmcOldManOutController extends BaseController {

    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private OmcOldOutService oldOutService;
    @Resource
    private OmcOldOutVarService omcOldOutVarService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private OmcExpenseTypeModelCodeService omcExpenseTypeModelCodeService;
    @Resource
    private OmcReturnFeeConfigService omcReturnFeeConfigService;
    @Resource
    private OmcGroupService omcGroupService;
    @Resource
    private OmcNursingRoomBindMapper omcNursingRoomBindMapper;
    @Resource
    private OmcNursingUserBindService omcNursingUserBindService;

    /**
     * 查询老人信息
     *
     * @return
     */
    @RequestMapping(value = "/queryOldmanList", method = RequestMethod.POST)
    public Wrapper queryOldmanList(@RequestBody OldOutOldmanQueryDto oldOutOldmanQueryDto) {

        /**
         * @author  chisj
         * @date    2021-08-17 16:11
         * @desc    修复班长在多个班组问题
         */
        // 获取用户是否为班长
        NursingGroup nursingGroup = new NursingGroup();
        nursingGroup.setUserId(getLoginAuthDto().getUserId());
        List<NursingGroup> nursingGroupList = omcGroupService.select(nursingGroup);
        if (PublicUtil.isEmpty(nursingGroupList)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10038001);
        }
        List<Long> nursingGroupIdList = Lists.newArrayList();
        for (NursingGroup ng : nursingGroupList) {
            nursingGroupIdList.add(ng.getId());
        }
        oldOutOldmanQueryDto.setNursingGroupIdList(nursingGroupIdList);
        oldOutOldmanQueryDto.setGroupId(getLoginAuthDto().getGroupId());

        // 根据班组查询看护的房间
        List<Integer> roomIdList = omcNursingRoomBindMapper
                .queryRoomIdListByNursingGroupIdList(nursingGroupIdList);
        if (PublicUtil.isEmpty(roomIdList)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10038011);
        }
        oldOutOldmanQueryDto.setRoomIdList(roomIdList);

        List<OldOutOldmanVo> oldmanList = oldOutService.queryOldmanList(oldOutOldmanQueryDto);

        // 根据机构Id查询退费项列表
        GroupPaymentFeeQueryDto groupPaymentFeeQueryDto = new GroupPaymentFeeQueryDto();
        groupPaymentFeeQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        groupPaymentFeeQueryDto.setModelCode(Constant.EXPENSE_TYPE_MODEL_CODE_OUT);
        List<GroupPaymentFeeVo> groupPaymentFeeVoList = omcExpenseTypeModelCodeService
                .queryGroupPaymentFeeByGroupId(groupPaymentFeeQueryDto);
        if (PublicUtil.isEmpty(groupPaymentFeeVoList)) {
            log.warn("机构无出院收费信息");
        }

        Map<String, Object> map = Maps.newHashMap();
        map.put("oldmanList", oldmanList);
        map.put("paymentList", groupPaymentFeeVoList);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), map);
    }

    /**
     * 查询老人出院退费天数
     *
     * @param oldOutDaysDto the old out days dto.
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/queryOldOutDaysVo", method = RequestMethod.POST)
    public Wrapper queryOldOutDaysVo(@RequestBody OldOutDaysDto oldOutDaysDto) {

        oldOutDaysDto.setGroupId(getLoginAuthDto().getGroupId());
        OldOutDaysVo oldOutDaysVo = omcReturnFeeConfigService.queryOldOutDaysVo(oldOutDaysDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), oldOutDaysVo);
    }

    /**
     * 出院申请
     * @param: [oldOutDto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @PostMapping(value = "/apply")
    public Wrapper apply(@RequestBody OldOutDto oldOutDto) {

        Integer result = oldOutService.apply(oldOutDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 服务部长确认
     */
    @PostMapping(value = "/serviceConfirm")
    public Wrapper serviceConfirm(@RequestBody OldOutConfirmDto oldOutConfirmDto) {

        Integer result = oldOutService.serviceConfirm(oldOutConfirmDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 医疗部长审批
     */
    @PostMapping(value = "/medicalApproval")
    public Wrapper medicalApproval(@RequestBody OldOutApprovalDto oldOutApprovalDto) {

        Integer result = oldOutService.medicalApproval(oldOutApprovalDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 接待部审批
     */
    @PostMapping(value = "/admitApproval")
    public Wrapper admitApproval(@RequestBody OldOutApprovalDto oldOutApprovalDto) {

        Integer result = oldOutService.admitApproval(oldOutApprovalDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 收费室确认
     */
    @PostMapping(value = "/chargeConfirm")
    public Wrapper chargeConfirm(@RequestBody OldOutConfirmDto oldOutConfirmDto) {

        Integer result = oldOutService.chargeConfirm(oldOutConfirmDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), result);
    }

    /**
     * 查询历史列表 - 分页查询
     */
    @PostMapping(value = "/queryHisTask")
    public Wrapper queryHisTask(@RequestBody OldOutQueryDto oldOutQueryDto) {

        List<Integer> states = Lists.newArrayList();
        states.add(OldOutConstant.OLD_OUT_STATE_SERVICE_REFUSE);
        states.add(OldOutConstant.OLD_OUT_STATE_CHARGE_CONFIRM);

        oldOutQueryDto.setStates(states);
        oldOutQueryDto.setGroupId(getLoginAuthDto().getGroupId());

        List<OldOutVo> oldOutVoList = oldOutService.queryListWithPage(oldOutQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), new PageInfo<>(oldOutVoList));
    }

    /**
     * 根据Id查询批注
     */
    @PostMapping(value = "/queryCommentById/{id}")
    public Wrapper queryCommentById(@PathVariable Long id) {

        List<MyCommentVo> myCommentVoList = oldOutService.queryCommentById(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),myCommentVoList);
    }


    /**
     * 查询待审批的列表 - 分页查询
     */
    @PostMapping(value = "/queryCurTask")
    public Wrapper queryCurTask(@RequestBody OldOutQueryDto oldOutQueryDto) {

        List<Integer> states = Lists.newArrayList();

        Map<String, Object> reviseVarMap = omcOldOutVarService
                .queryVarByGroupId(getLoginAuthDto().getGroupId());

        // 获取当前用户角色
        List<RpcRoleVo> roleVoList = uacRpcService.queryRoleListByUserId(getLoginAuthDto().getUserId());
        for (RpcRoleVo r : roleVoList) {
            if (reviseVarMap.get(OldOutConstant.OLD_OUT_VAR_SERVICE).toString().contains(r.getRoleCode())) {
                // 服务部长角色（服务部长） ===> 查看提交申请的任务
                states.add(OldOutConstant.OLD_OUT_STATE_APPLY);
            }
            if (reviseVarMap.get(OldOutConstant.OLD_OUT_VAR_MEDICAL).toString().contains(r.getRoleCode())) {
                // 医疗部长角色(医疗部长) ===> 查看服务部长确认的任务
                states.add(OldOutConstant.OLD_OUT_STATE_SERVICE_AGREE);
            }
            if (reviseVarMap.get(OldOutConstant.OLD_OUT_VAR_ADMIT).toString().contains(r.getRoleCode())) {
                // 接待角色（接待员、接待部长、评估员） ===> 查看医疗部长确认的任务
                states.add(OldOutConstant.OLD_OUT_STATE_MEDICAL_AGREE);
            }
            if (reviseVarMap.get(OldOutConstant.OLD_OUT_VAR_CHARGE).toString().contains(r.getRoleCode())) {
                // 收费员角色（收费员） ===> 查看接待确认的任务
                states.add(OldOutConstant.OLD_OUT_STATE_ADMIT_CONFIRM);
            }
        }

        if (PublicUtil.isEmpty(states) || states.size() < 1) {
            return WrapMapper.ok(new PageInfo<>(Lists.newArrayList()));
        }

        // 对states进行去重
        PublicUtil.removeDuplicate(states);

        oldOutQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        oldOutQueryDto.setStates(states);

        List<OldOutVo> oldOutVoList = oldOutService.queryListWithPage(oldOutQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),new PageInfo<>(oldOutVoList));
    }


    /**
     * 出院申请列表 - 分页查询
     */
    @PostMapping(value = "/queryListWithPage")
    public Wrapper queryListWithPage(@RequestBody OldOutQueryDto oldOutQueryDto) {

        /**
         * @author  chisj
         * @date    2021-08-17 16:18
         * @desc    修复班长在多个班组的问题
         */
        OmcNursingUserBind nursingUserBind = new OmcNursingUserBind();
        nursingUserBind.setUserId(getLoginAuthDto().getUserId());
        List<OmcNursingUserBind> nursingUserBindList = omcNursingUserBindService.select(nursingUserBind);

        if (PublicUtil.isNotEmpty(nursingUserBindList)) {
            List<Long> nursingGroupIdList = Lists.newArrayList();
            for (OmcNursingUserBind onub : nursingUserBindList) {
                nursingGroupIdList.add(onub.getNursingGroupId());
            }
            oldOutQueryDto.setNursingGroupIdList(nursingGroupIdList);
        }
        oldOutQueryDto.setGroupId(getLoginAuthDto().getGroupId());

        List<OldOutVo> oldOutVoList = oldOutService.queryListWithPage(oldOutQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),new PageInfo<>(oldOutVoList));
    }

    /**
     * 根据Id查出出院申请详情
     */
    @PostMapping(value = "/queryById/{id}")
    public Wrapper queryById(@PathVariable Long id) {

        OldOutVo oldOutVo = oldOutService.queryById(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),oldOutVo);
    }

}
